﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using ROrganizer.Client.Files;

namespace ROrganizer.Client
{
    internal class MetaSerializer
    {
        public MetaEntry[] Deserialize(XDocument document)
        {
            var query = from element in document.Root.Elements()
                        select MetaSerializer.Deserialize(element);

            return query.ToArray();
        }

        public MetaEntry Deserialize(XDocument document, string file)
        {
            var query = from element in document.Root.Elements()
                        where element.Element("File").Value == file
                        select MetaSerializer.Deserialize(element);

            return query.FirstOrDefault();
        }

        private static MetaEntry Deserialize(XElement element)
        {
            return new MetaEntry
            {
                File = new FileEntry
                {
                    Path = element.Element("File").Value,
                    Timestamp = DateTime.Parse(element.Element("File").Attribute("Timestamp").Value).ToUniversalTime(),
                },
                Info = new MetaInfo
                {
                    Size = Int64.Parse(element.Element("Size").Value),
                    Width = Int32.Parse(element.Element("Width").Value),
                    Height = Int32.Parse(element.Element("Height").Value),
                    Runtime = Int32.Parse(element.Element("Runtime").Value),
                }
            };
        }

        public void Update(XDocument document, params MetaEntry[] entries)
        {
            foreach (var entry in entries)
            {
                var element = document.Root.Elements().FirstOrDefault(x => x.Element("File").Value == entry.File.Path);
                var created = MetaSerializer.Serialize(entry);

                if (element != null)
                {
                    element.ReplaceWith(created);
                }
                else
                {
                    document.Root.Add(created);
                }
            }
        }

        private static XElement Serialize(MetaEntry entry)
        {
            return new XElement("HashEntry",
                        new XElement("File",
                            new XCData(entry.File.Path),
                            new XAttribute("Timestamp", entry.File.Timestamp)),
                        new XElement("Size", entry.Info.Size),
                        new XElement("Width", entry.Info.Width),
                        new XElement("Height", entry.Info.Height),
                        new XElement("Runtime", entry.Info.Runtime));
        }
    }
}
